import os.path
import pandas as pd
from joblib import Parallel, delayed
from research.factor import factordata
from docx import Document
from jili.report.chart_boxplot import chart_boxplot
from jili.report.statistics_info import statistics_info
from jili.tool.round_all import round_all
from docx.shared import Inches
from jili.report.gen_html import html
def report_factor2doc(fnames,furl,docurl,objs,start,end):
    fnames0={}
    if isinstance(fnames,list):
        for i in fnames:
            fnames0[i]=i
    else:
        fnames0=fnames
    for obj in objs:
        # 创建一个新的Word文档
        doc = Document()
        for k,v in fnames0.items():
            f=factordata(k,furl)
            data=f.get_all(name=k,start=start,end=end)
            if obj=="all":
                data0=data
            else:
                data0={}
                ishave=False
                for d,fv in data.items():
                    if obj in fv.keys():
                        ishave=True
                    if ishave:
                        data0[d]=fv.get(obj,None)
            d0=pd.Series(data0)
            doc.add_heading("因子"+v+"("+k+")"+"统计描述")
            chart_boxplot(d0, url=r"F:/fig0.png")
            doc.add_picture(r"F:/fig0.png",width=Inches(6.5))
            r = statistics_info(d0)
            r=round_all(r)
            import math
            all0 = []
            for k, v in r.items():
                all0.append(k)
                all0.append(v)
            n0 = len(all0)
            n1 = math.ceil(n0 / 6)
            table = doc.add_table(rows=n1, cols=6)
            n = 0
            for i in range(n1):
                for j in range(6):
                    if n < n0:
                        cell = table.cell(i, j)
                        cell.text = str(all0[n])
                    n = n + 1
        docurl0=os.path.join(docurl,obj+"因子统计描述.docx")
        doc.save(docurl0)
def deal_report(v,docurl,fname,obj,sample,stdn,flags_info,lastn,boxn,percentiles):
    d0 = pd.Series(v)
    d0=d0.iloc[-lastn:]
    baseurl = os.path.dirname(docurl)
    figurl = os.path.join(baseurl, "fig", fname + "_" + obj + ".png")
    chart_boxplot(d0, url=figurl,sample=sample,stdn=stdn,flags_info=flags_info,boxn=boxn)
    figurl1 = "fig/" + fname + "_" + obj + ".png"
    r = statistics_info(d0, sample=sample, isdf=True,percentiles=percentiles)
    r = round_all(r)
    return figurl1,r
def report_factor2html(fnames,furl,docurl,objs,start,end,sample=[600,30],stdn=True,pool_n=0,lastn=600,boxn=[600,30],percentiles=[5,20,80,95],flags_info={},remark_info={}):
    fnames0={}
    if isinstance(fnames,list):
        for i in fnames:
            fnames0[i]=i
    else:
        fnames0=fnames
    html0=html(htmlstr="",file="",name="描述统计信息")
    baseurl = os.path.abspath(os.path.dirname(docurl))
    figurl0 = os.path.join(baseurl, "fig")
    if not os.path.exists(figurl0):
        os.makedirs(figurl0)
    data0 = {}
    for k,v in fnames0.items():
        f=factordata(k,furl)
        data=f.get_all(name=k,start=start,end=end)
        for obj in objs:
            if obj=="all":
                if obj not in data0.keys():
                    data0[obj] = {}
                data0[obj][k]=data
            else:
                ishave=False
                for d,fv in data.items():
                    if obj in fv.keys():
                        ishave=True
                    if ishave:
                        if obj not in data0.keys():
                            data0[obj]={}
                        if k not in data0[obj].keys():
                            data0[obj][k]={}
                        data0[obj][k][d]=fv.get(obj,None)
    rst={}
    ll=[]
    for obj,vv in data0.items():
        flags_info0=flags_info.get(obj,{})
        for k,v in vv.items():
            flags_info1 = flags_info0.get(k, {})
            if pool_n>0:
                ll.append((v,docurl,k,obj,sample,stdn,flags_info1,lastn,boxn,percentiles))
            else:
                figurl1,r=deal_report(v,docurl,k,obj,sample,stdn,flags_info1,lastn,boxn,percentiles)
                if obj not in rst.keys():
                    rst[obj]={}
                rst[obj][k]=(figurl1,r)
    if ll:
        results = Parallel(n_jobs=pool_n)(delayed(deal_report)(*i) for i in ll)
        n=0
        for obj, vv in data0.items():
            rst[obj]={}
            for k, v in vv.items():
                rst[obj][k]=results[n]
                n=n+1
    for obj,vv in rst.items():
        html0.addtitle(obj + "统计描述", titletype="h2", align="left")
        remark_info0 = remark_info.get(obj, {})
        for k, v in vv.items():
            remark_info1 = remark_info0.get(k, {})
            figurl1, r=v
            fname=fnames0[k]
            html0.addtitle(obj+"因子"+fname+"("+k+"):",titletype="h3",align="left")
            html0.addfig(figurl1)
            for kk,vv in remark_info1.items():
                msg=kk+":"+vv
                html0.addtext(msg)
            html0.addtable(r)
    html0.save(docurl)
if __name__=="__main__":
    # report_factor2doc(fnames=["stock_bais_byhigh_20_60","stock_bais_byhigh_10_60"], furl=r"G:/factor/stock_wave/k1d", docurl=r'F:/', objs=["002594"], start="20190102", end=None)
    report_factor2html(fnames=["stock_bais_byhigh_20_60","stock_bais_byhigh_10_60"], furl=r"G:/factor/stock_wave/k1d", docurl=r'F:/html/html1/sample.html', objs=["002594"], start="20190102", end=None,pool_n=6,last=600)